{% extends "generic/page.html" %}

{% block head_additions %}
    <div class="container">
        <div class="level">
            <div class="level-item has-text-centered">
                <div>
                    <p class="heading">Crawls</p>
                    <p class="title" id="crawls">&nbsp;</p>
                </div>
            </div>
            <div class="level-item has-text-centered">
                <div>
                    <p class="heading">Number of aggregated hours</p>
                    <p class="title" id="hours">&nbsp;</p>
                </div>
            </div>
            <div class="level-item has-text-centered">
                <div>
                    <p class="heading">Number of aggregated days</p>
                    <p class="title" id="days">&nbsp;</p>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block body %}
    <div class="tile is-ancestor">
        <div class="tile is-vertical is-parent">
            <article class="tile is-child notification">
                <p class="title">Seen nodes</p>
                <div class="">
                    <canvas id="up-down-chart"></canvas>
                </div>

            </article>
            <article class="tile is-child notification">
                <p class="title">Groups</p>
                <p class="subtitle">IP addresses grouped by prefix sharing 18 bits minimum</p>
                <div class="">
                    <canvas id="groups-chart"></canvas>
                </div>

            </article>
        </div>
        <div class="tile is-vertical is-parent">
            <article class="tile is-child notification">
                <p class="title">Aliases</p>
                <p class="subtitle">IP addresses holding more than 2 Node IDs</p>
                <div class="">
                    <canvas id="aliases-chart"></canvas>
                </div>

            </article>
            <article class="tile is-child notification">
                <p class="title">Subnets</p>
                <p class="subtitle">/24 subnets containing more than 24 IP addresses</p>
                <div class="">
                    <canvas id="subnets-chart"></canvas>
                </div>

            </article>
        </div>
    </div>
{% endblock %}

{% block scripts %}
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/luxon"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon"></script>

    <script>
        let bulma = {
            white: 'hsl(0, 0%, 100%)',
            black: 'hsl(0, 0%, 4%)',
            light: 'hsl(0, 0%, 96%)',
            dark: 'hsl(0, 0%, 21%)',
            primary: 'hsl(171, 100%, 41%)',
            link: 'hsl(217, 71%, 53%)',
            info: 'hsl(204, 86%, 53%)',
            success: 'hsl(141, 53%, 53%)',
            warning: 'hsl(48, 100%, 67%)',
            danger: 'hsl(348, 100%, 61%)'
        };

        let hsla = (color, alpha) => `hsla${color.substring(3, color.length - 1)},${alpha.toString()})`

        function fillLevel(data) {
            let total_crawls = 0;
            let days = {};
            for (const [k, v] of Object.entries(data)) {
                total_crawls += v.aggregated_files;
                days[k.substring(0, 10)] = null;
            }
            document.getElementById("crawls").innerHTML = total_crawls.toLocaleString();
            document.getElementById("hours").innerHTML = Object.keys(data).length.toLocaleString();
            document.getElementById("days").innerHTML = Object.keys(days).length.toLocaleString();
        }

        let fillBlanks = data => {
            fillLevel(data);
            fillCharts(extractSeries(data));
        };

        let createGraph = (id, data) => {
            new Chart(document.getElementById(id), {
                type: 'line',
                data: data,
                options: {
                    animation: false,
                    plugins: {
                        legend: {
                            display: (data.datasets.length > 1)
                        },
                        filler: {
                            propagate: true
                        }
                    },
                    scales: {
                        x: {
                            type: 'time',
                        },
                        y: {
                            beginAtZero: true
                        }
                    },
                    elements: {
                        line: {
                            cubicInterpolationMode: 'monotone',
                            tension: .4
                        },
                        point: {
                            radius: 0,
                            pointHitRadius: 8
                        }
                    }
                }
            })
        };

        let keyToDate = key => new Date(Date.UTC(parseInt(key.substring(6, 10)), parseInt(key.substring(3, 5)) - 1, parseInt(key.substring(0, 2)), parseInt(key.substring(11))));

        let extractSeries = crawl_history_data => {
            let series = {ups: [], groups: [], aliases: [], subnets: [], labels: []}
            let entries = Object.entries(crawl_history_data)
            entries.sort(([ka,], [kb,]) => (keyToDate(kb).getTime() < keyToDate(ka).getTime()) ? 1 : -1)
            for (const [k, v] of entries) {
                series.ups.push(v.up_count)
                series.groups.push(v.groups_count)
                series.aliases.push(v.aliases_count)
                series.subnets.push(v.subnets_count)
                series.labels.push(keyToDate(k))
            }

            return series
        };

        let dataset = (label, data, color = bulma.primary) => ({
            label: label,
            data: data,
            borderColor: color,
            fill: {target: 'start', above: hsla(color, 0.2)}
        });

        let chartContent = (labels, datasets) => ({labels: labels, datasets: datasets});

        let fillCharts = series => {
            console.log(series)
            createGraph('up-down-chart', chartContent(series.labels, [dataset("up nodes", series.ups, bulma.success)]))
            createGraph('groups-chart', chartContent(series.labels, [dataset("groups", series.groups)]))
            createGraph('aliases-chart', chartContent(series.labels, [dataset("aliases", series.aliases, bulma.info)]))
            createGraph('subnets-chart', chartContent(series.labels, [dataset("subnets", series.subnets, bulma.link)]))

        };

        fetch('{{url_for("stats")}}')
            .then(response => response.json())
            .then(data => fillBlanks(data));

    </script>
{% endblock %}